package simorg.actions;

import org.dom4j.Document;
import org.dom4j.Element;

import simorg.controller.AdminController;
import simorg.domain.User;
import simorg.domain.persistence.UserTable;
import simorg.util.PasswordHash;
import simorg.view.ModelView;
import simorg.view.Page;
import simorg.view.SessionAttribute;
import simorg.view.WebSessionContext;

public class AdminLogin extends Action {
	
	public static final String actionName = "login";
	public AdminLogin() {
		super(actionName);
		this.controllerName = AdminController.controllerName;
	}
	
	
	
	public ModelView process(WebSessionContext wc) throws Exception  {
		String username = wc.getRequestParameter("username");
		String password = wc.getRequestParameter("password");
		Document xmlDoc = this.getBaseXml(wc);
		
		// If they are both blank, display blank login page.
		if ( username == null && password == null ) {
			return new ModelView(Page.AdminLogin, xmlDoc);
		}
		// If one is blank, display login page with error.
		else if ( username == null || password == null) {
			Element login = xmlDoc.getRootElement().addElement( "login" );
			login.addAttribute("username", username==null?"":username);
			return new ModelView(Page.AdminLogin, xmlDoc);
		}
		
		User user = UserTable.findByUsernameAndPassword(wc.getDbConnection(), username, PasswordHash.getHash(password));
		// If password/username don't authenticate, display login page with error
		if ( user == null ) {
			Element login = xmlDoc.getRootElement().addElement( "login" );
			login.addAttribute("username", username==null?"":username);
			login.addAttribute("error", "Invalid username/password");
			return new ModelView(Page.AdminLogin, xmlDoc);
		}
		// If successful, set session object and redirect to View operation
		else {
			wc.setSessionAttribute(SessionAttribute.DefaultAction, new CourseList());
			wc.setSessionAttribute(SessionAttribute.User, user);
			wc.redirectAdmin(new CourseList());
			return null;
		}
	}
	
	
	
}
